package com.leyou.page.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.api.GoodsApi;
import com.leyou.item.pojo.*;
import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.SpecificationClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: taft
 * @Date: 2018-10-21 12:27
 */
@Service
public class PageService {

    @Autowired
    private GoodsApi goodsApi;

    @Autowired
    private SpecificationClient specificationClient;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private CategoryClient categoryClient;


    public Map<String, Object> loadData(Long id) {

        Map<String,Object> resultMap = new HashMap<>();

        //查询spu
        Spu spu = goodsApi.querySpuById(id);

        resultMap.put("spu",spu);

        //查询sku的详情信息
        SpuDetail spuDetail = goodsApi.querySpuDetailById(id);

        resultMap.put("spuDetail",spuDetail);

        List<Sku> skuList = goodsApi.querySkuBySpuId(id);

        resultMap.put("skus",skuList);


        //规格参数的值
        Map<Long, Object> genericSpecMap = JsonUtils.parseMap(spuDetail.getGenericSpec(), Long.class, Object.class);
        Map<Long, List<String>> specialSpecMap = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });

//        resultMap.put("genericSpecMap",genericSpecMap);
//
//        resultMap.put("specialSpecMap",specialSpecMap);


        //规格参数的key
        List<SpecGroup> specGroups = specificationClient.querySpecsByCid(spu.getCid3());
        resultMap.put("groups",specGroups);

        //查询所有的特有规格参数
        List<SpecParam> specParams = this.specificationClient.querySpecParam(null, spu.getCid3(), null, false);

        //存入规格参数值得key：value对应关系
        Map<Long,String> specMap = new HashMap<>();//1：品牌，2：型号

        for (SpecParam specParam : specParams) {
            specMap.put(specParam.getId(),specParam.getName());
        }

        resultMap.put("paramMap",specMap);

        //TODO 处理品牌信息，以及分类信息，

        Brand brand = this.brandClient.queryBrandById(spu.getBrandId());

        resultMap.put("brand",brand);

        //分类信息

        List<Category> categories = new ArrayList<>();

        List<String> categoryNames = this.categoryClient.queryNameByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));

        List<Long> ids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());

        for (int i = 0; i < ids.size(); i++) {
            Category category = new Category();
            category.setId(ids.get(i));
            category.setName(categoryNames.get(i));

            categories.add(category);
        }

        resultMap.put("categories",categories);

        return resultMap;


    }
}
